package plugin

import (
	"fmt"
	"golang.org/x/crypto/ssh"
	"strings"
	"sync"
)

type ResultInfo struct {
	IP string 	`json:"IP"`
	Cmd string  `json:"命令"`
	Result interface{} `json:"结果"`

}
var cmderr string

func SshClient(IP ,user,password ,cmd string,wg *sync.WaitGroup) (ResultInfo,error){
	//使用秘钥登录
	//keyString,_ := ioutil.ReadFile("C:\\Users\\go\\id_rsa")
	//keyRsa , _ := ssh.ParsePrivateKey(keyString)
	//publickey := ssh.PublicKeys(keyRsa)
    defer wg.Done()
	ip := strings.Split(IP,":")
	//跟服务器建立连接
	client,err:= ssh.Dial("tcp",IP,&ssh.ClientConfig{
		User: user,
		Auth: []ssh.AuthMethod{ssh.Password(password)},
		//Auth: []ssh.AuthMethod{publickey},   // 秘钥登录
		HostKeyCallback: ssh.InsecureIgnoreHostKey(),
	})

	if err != nil{
		fmt.Println("ssh err :",err)
	}

	//
	session,err := client.NewSession()
	if err != nil {
		fmt.Printf("session err: %s",err)
	}
	defer session.Close()

	b , err := session.CombinedOutput(cmd)
	if err != nil{
		//fmt.Printf("命令:<= %s => 错误: %s",cmd ,string(b))
		be := fmt.Sprintf("%s",err)
		status := strings.Fields(be)[4]
		fmt.Println("存在错误，错误码:",status)

	}
	//cmderr := fmt.Sprintf("执行命令:<= %s => 错误: %s",cmd ,err)

	r := ResultInfo{
		Result: string(b),
		Cmd: cmd,
		IP: ip[0],
	}

	info := r
	if err != nil {
		fmt.Printf("%s 命令:<= %s => 错误: %s\n",info.IP,info.Cmd,err)
		fmt.Println("返回结果:",info.Result)
	}else {
		fmt.Printf("%s 连接成功====>\n",info.IP)
		fmt.Println("执行命令:",info.Cmd)
		fmt.Println("返回结果:",info.Result)
	}
	return r ,err
}

//不并发的副本
func Sshclient(IP ,user,password ,cmd string) (ResultInfo,error){
	//使用秘钥登录
	//keyString,_ := ioutil.ReadFile("C:\\Users\\go\\id_rsa")
	//keyRsa , _ := ssh.ParsePrivateKey(keyString)
	//publickey := ssh.PublicKeys(keyRsa)
	ip := strings.Split(IP,":")
	//跟服务器建立连接
	client,err:= ssh.Dial("tcp",IP,&ssh.ClientConfig{
		User: user,
		Auth: []ssh.AuthMethod{ssh.Password(password)},
		//Auth: []ssh.AuthMethod{publickey},   // 秘钥登录
		HostKeyCallback: ssh.InsecureIgnoreHostKey(),
	})

	if err != nil{
		fmt.Println("ssh err :",err)
	}

	//
	session,err := client.NewSession()
	if err != nil {
		fmt.Printf("session err: %s",err)
	}
	defer session.Close()

	b ,err := session.CombinedOutput(cmd)
	if err != nil{
		//fmt.Printf("命令:<= %s => 错误: %s",cmd ,string(b))
		be := fmt.Sprintf("%s",err)
		status := strings.Fields(be)[4]
		fmt.Println("存在错误，错误码:",status)
	}
	//cmderr := fmt.Sprintf("执行命令:<= %s => 错误: %s",cmd ,err)

	r := ResultInfo{
		Result: string(b),
		Cmd: cmd,
		IP: ip[0],
	}

	info := r
	if err != nil {
		fmt.Printf("%s 命令:<= %s => 错误: %s\n",info.IP,info.Cmd,err)
		fmt.Println("返回结果:",info.Result)
	}else {
		fmt.Printf("%s 连接成功====>\n",info.IP)
		fmt.Println("执行命令:",info.Cmd)
		fmt.Println("返回结果:",info.Result)
	}
	return r ,err
}
